package com.mvvm.store.ui.stockup;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseActivity;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.basebean.ScanStockBean;
import com.mvvm.store.bean.basebean.StockUpInfoBean;
import com.mvvm.store.bean.basebean.StockUpScanInfoBean;
import com.mvvm.store.bean.basebean.StockUpSubmitParams;
import com.mvvm.store.bean.basebean.StockUpSubmitResultBean;
import com.mvvm.store.databinding.FragmentDeliveryManagerBinding;
import com.mvvm.store.databinding.FragmentStockManagerBinding;
import com.mvvm.store.roombatabase.ScanStockDao;
import com.mvvm.store.roombatabase.ScanStockDatabase;
import com.mvvm.store.roombatabase.StockUpInfoDao;
import com.mvvm.store.roombatabase.StockUpScanDao;
import com.mvvm.store.roombatabase.StockUpScanDatabase;
import com.mvvm.store.roombatabase.StoreHouseDatabase;
import com.mvvm.store.ui.delivery.DeliveryInfoFragment;
import com.mvvm.store.ui.delivery.DeliverySweptFragment;
import com.mvvm.store.ui.delivery.adapter.DeliveryPagerAdapter;
import com.mvvm.store.ui.stockup.adapter.StockPagerAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by leo
 * on 2020/10/21.   出库管理
 */
public class StockUpActivity extends BaseActivity<StockUpViewModel, FragmentStockManagerBinding> {

    private List<Fragment> fragments=new ArrayList<>();

    private List<CharSequence> titleslist=new ArrayList<>();

    private String[] titles = new String[]{"备货信息", "已扫物料标签"};

    public static boolean isStockUpSubmitScan=false;  //扫码提交用的

    private String orderId;

    private StockUpScanDao stockUpScanDao;
    private StockUpInfoDao stockUpInfoDao;
    private ScanStockDao scanStockDao;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_stock_manager;
    }

    @Override
    protected void processLogic() {
        isStockUpSubmitScan=false;
        stockUpScanDao= StockUpScanDatabase.getInstance(this).stockUpScanDao();
        stockUpInfoDao= StoreHouseDatabase.getInstance(this).stockUpDao();
        scanStockDao= ScanStockDatabase.getInstance(this).scanStockDao();
        SharedPreferences sharedPreferences =this.getSharedPreferences("stockInfo", MODE_PRIVATE);
        orderId=sharedPreferences.getString("orderId","");

        binding.leoTitleBar.bar_right_btn.setVisibility(View.VISIBLE);
        binding.leoTitleBar.bar_left_btn.setBackgroundResource(R.mipmap.return_images);
        for (int i=0;i<titles.length;i++){
            titleslist.add(titles[i]);
        }

        StockUpInfoFragment stockInfo=StockUpInfoFragment.newInstance("stockInfo",binding.viewPager);
        StockUpSweptFragment stockSwept=StockUpSweptFragment.newInstance("stockSwept",binding.viewPager);
        fragments.add(stockInfo);
        fragments.add(stockSwept);
        StockPagerAdapter stockPagerAdapter=new StockPagerAdapter(this.getSupportFragmentManager(),fragments,titleslist);
        binding.viewPager.setAdapter(stockPagerAdapter);
        binding.tablayout.setupWithViewPager(binding.viewPager);
        binding.tablayout.setTabMode(TabLayout.MODE_FIXED);
        binding.tablayout.getTabAt(0).select();
    }

    @Override
    protected void setListener() {
        binding.leoTitleBar.bar_left_btn.setOnClickListener(this::onClick);
        binding.leoTitleBar.bar_right_btn.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bar_left_btn:
                this.finish();
                break;
            case R.id.bar_right_btn:
                stockUpSubmit();
                break;
            default:
                break;
        }
    }
    //点击提交物料信息
    private void stockUpSubmit(){
        if(isSubmit()){
            SharedPreferences sharedPreferences =this.getSharedPreferences("stockUpUserInfo", MODE_PRIVATE);
            String userId=sharedPreferences.getString("stockUpUserId","");
            if("".equals(userId)){
                //提示他去扫码验证身份
                ToastUtils.showToast("提交前先请扫码验证身份");
                isStockUpSubmitScan=true;
            }else {
                List<StockUpSubmitParams> stockUpSubmitParamsList=new ArrayList<>();
                 //物料满足了,备货员也录入成功了
                StockUpSubmitParams stockUpSubmitParams=new StockUpSubmitParams();
                //根据订单号查询订单信息
                List<StockUpInfoBean> stockUpInfoBeansSubmit=stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
                stockUpSubmitParams.setStockClerk(userId);
                stockUpSubmitParams.setStockOrderNo(orderId);
                //stockUpSubmitParams.setStockStatus("1");
                for (int i=0;i<stockUpInfoBeansSubmit.size();i++) {
                    stockUpSubmitParams.setSupplierName(stockUpInfoBeansSubmit.get(i).getSupplierName());
                }
               /* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                //获取当前时间
                Date date = new Date(System.currentTimeMillis());
                String dataTime=simpleDateFormat.format(date);
                stockUpSubmitParams.setStockTime(dataTime);*/
                stockUpSubmitParamsList.add(stockUpSubmitParams);
                //调用接口提交数据
                mViewModel.stockUpSubmit(stockUpSubmitParamsList).observe(this,resourse->resourse.handler(new OnCallback<StockUpSubmitResultBean>() {
                    @Override
                    public void onSuccess(StockUpSubmitResultBean data) {
                        if("200".equals(data.getSubmitCode())) {
                            if (!TextUtils.isEmpty(data.getSubmitMsg())) {
                                ToastUtils.showToast(data.getSubmitMsg());
                            }
                            //成功
                            List<StockUpInfoBean> stockUpInfoBeansDelete = stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
                            for (int i = 0; i < stockUpInfoBeansDelete.size(); i++) {
                                List<ScanStockBean> scanStockBeanListDelete= scanStockDao.getScanStockBeanByOddNumber(stockUpInfoBeansDelete.get(i).getOddNumber());
                                for (int a=0;a<scanStockBeanListDelete.size();a++){
                                    scanStockDao.delete(scanStockBeanListDelete.get(a));
                                }
                                List<StockUpScanInfoBean> stockUpScanInfoBeansDelete = stockUpScanDao.getAll(stockUpInfoBeansDelete.get(i).getOrderNumber());
                                for (int j = 0; j < stockUpScanInfoBeansDelete.size(); j++) {
                                    stockUpScanDao.delete(stockUpScanInfoBeansDelete.get(j));
                                }
                                stockUpInfoDao.delete(stockUpInfoBeansDelete.get(i));
                            }
                            //清除SP
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.clear().commit();
                            //设置scan为false
                            isStockUpSubmitScan = false;
                            finish();
                        }else {
                            ToastUtils.showToast(data.getDescription()+"");
                        }
                    }
                }));
            }

        }else {
            ToastUtils.showToast("未满足提交物料的条件,请核对好再提交");
        }

    }

    private boolean isSubmit(){
        List<Boolean> isBool=new ArrayList<>();
        //查询订单表是否满足备货提交的条件
        List<StockUpInfoBean>  stockUpInfoBeans=stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
        if(stockUpInfoBeans.size()>0){

            for (int i=0;i<stockUpInfoBeans.size();i++){
                if(stockUpInfoBeans.get(i).getSumNumber()==stockUpInfoBeans.get(i).getRealToNumber()){
                    isBool.add(true);
                }else {
                    isBool.add(false);
                }
            }
            for (boolean isBools: isBool){
                if(!isBools){
                    return false;
                }
            }
            return true;
        }else {
            ToastUtils.showToast("没有可提交的物料");
        }
        return false;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
